#!/bin/bash

CPP_VERSION_FILE=src/version.h
TMP_FILE=.tmp.h
# empty $TMP_FILE
> $TMP_FILE

svn info &> /dev/null
if (($?)); then
    git status &> /dev/null < /dev/null
    if (($?)); then
        # unknow error, not svn or git
        echo 'neither svn nor git\nunknow_version' >> $TMP_FILE
    else
        # for git
        echo 'GIT: '`git remote -v | grep fetch | awk '{print $2}'` >> $TMP_FILE
        branch=`git status | head -n 1 | awk '{print $NF}'`
        echo 'LastCommit:' >> $TMP_FILE
        git log -1 | while read -r line ; do echo '\t'$line;done >> $TMP_FILE
    fi
else
    # for svn
    echo SVN: `svn info | grep URL | awk '{print $2}'` >> $TMP_FILE
    echo 'Revision  : '`svn info | grep Revision | awk '{print $2}'` >> $TMP_FILE
    echo 'LastCommit:' >> $TMP_FILE
    svn log -l1 | grep -v '\-\-\-\-' | while read -r line; do echo '\t'$line; done >> $TMP_FILE
fi

IFS=$'\n'
> $CPP_VERSION_FILE
echo '/* this version file is generated by version.sh,'>> $CPP_VERSION_FILE
echo '  DONOT edit this file. */' >> $CPP_VERSION_FILE
echo "static const char * kBranch = \"$branch\";" >> $CPP_VERSION_FILE
echo 'static const char * kVersionInfo = \' >> $CPP_VERSION_FILE
while read -r line; do info=`echo $line | sed 's/"//g'`; echo \"$info\\n\" >> $CPP_VERSION_FILE ; done  < $TMP_FILE
echo ';/* EOF */' >> $CPP_VERSION_FILE
rm -rf $TMP_FILE
